package com.hnu.controller;

import cn.hutool.core.io.FileUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@CrossOrigin //服务器端解决跨域
@RequestMapping("/photo")
@RestController
public class PhotoController {

    @GetMapping("/{fileName}")
    public void photo(@PathVariable String fileName , HttpServletResponse response) throws IOException {

        String file = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\images\\"+fileName;

        File file1 = new File(file);

        ServletOutputStream outputStream = response.getOutputStream();

        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("application/octet-stream");
        outputStream.write(FileUtil.readBytes(file1));
        outputStream.flush();
        outputStream.close();
    }
}
